package com.jqb.jspcart.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CreateCode extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//禁用各种浏览器的缓存
		response.setHeader("Cache-Control", "nocache");
		response.setHeader("Pragma", "nocache");
		response.setDateHeader("Expires", -1);
		//设置回送格式为图片
		response.setHeader("Content-Type", "image/jpeg");
		//在缓存中建立图片
		BufferedImage image = new BufferedImage(60,15,BufferedImage.TYPE_INT_RGB);
		//获得画笔
		Graphics g = image.getGraphics();
		//画个矩形覆盖黑框
		g.setColor(new Color(85,85,85));
		g.fillRect(0, 0, 60, 15);
		//设置画笔画随机数
		g.setColor(Color.WHITE);
		g.setFont(new Font(Font.DIALOG,Font.BOLD,15));
		
		StringBuffer checkcode = new StringBuffer();
		for(int i=0;i<4;i++){
			int s= new Random().nextInt(10);
			checkcode.append(s);
		}
		request.getSession().setAttribute("checkcode", checkcode.toString());
		g.drawString(checkcode.toString(), 5, 15);
		
		ImageIO.write(image, "jpg", response.getOutputStream());
	}
}
